package com.baseweb.webadmin.controller.web;

import com.baseweb.webadmin.alipay.config.AlipayConfig;
import com.baseweb.webadmin.alipay.util.AlipaySubmit;
import com.baseweb.webadmin.bankpay.util.*;
import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.ByUserOrderDetailInfoBvo;
import com.baseweb.webadmin.core.model.bvo.ByUserOrderInfoBvo;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.RoleService;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhouxin on 2017/7/13.
 */
@Controller
@RequestMapping("/htmlWeb/")
public class OrderManagerController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(OrderManagerController.class);

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    private String PREFIX = "/htmlWeb/";

    @RequestMapping(value = "/orderManagerList")
    @ResponseBody
    public ResultPage<ByUserOrderInfoBvo> getOrderManagerList(HttpServletRequest request,@RequestParam(value = "bizUserId", required = false) Integer bizUserId,
                                                              @RequestParam(value = "status", required = false) Integer status,
                                                              @RequestParam(value = "payStatus", required = false) Integer payStatus,
                                                              @RequestParam(value = "startTime",required = false)String startTime,
                                                              @RequestParam(value = "endTime",required = false)String endTime,
                                                              @RequestParam(value = "professionName",required = false)String professionName,
                                                              @RequestParam(value = "userFlag", required = false) Integer userFlag,ByUserOrderInfoBvo user,
                                                              RequestPage requestPage) {
        Object temp = request.getSession().getAttribute("login_id");
        Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());
        String area = "";
        Integer guserId = null;
        ByUserOrderInfoBvo byUserOrderInfoBvo = null;
        if(userFlag != null){
            if(userFlag == 1){//订单中心
                String userType = String.valueOf(request.getSession().getAttribute("login_type"));
                if(!(UserType.SUPER_ADMIN.getCode() + "").equals(userType)){
                    List<ByOpenCity> byOpenCityList = userService.findAllAreaByUserId(userId);
                    int i = 0;
                    for(ByOpenCity city : byOpenCityList){
                        if(i == 0){
                            area += "'" + city.getArea() + "'";
                        }else{
                            area += ",'" + city.getArea() + "'";
                        }
                        i++;
                    }
                }else if((UserType.ADMIN.getCode() + "").equals(userType)){
                    guserId = userId;
                }
                userId = null;
                bizUserId = null;
                byUserOrderInfoBvo = userOrderService.sumPriceFromOrder(userId,area,guserId,bizUserId,status,payStatus,startTime,endTime,user,professionName,requestPage.getStart(), requestPage.getPageSize());
            }else if(userFlag == 2){//商家用户
                bizUserId = userId;
                userId = null;
            }else{//个人用户
                bizUserId = null;
            }
        }
        List<ByUserOrderInfoBvo> list = userOrderService.selectOrderListByPage(userId,area,guserId,bizUserId,status,payStatus,startTime,endTime,user,professionName,requestPage.getStart(), requestPage.getPageSize());
        Integer total = userOrderService.selectOrderListByBizUserCount(userId,area,guserId, bizUserId, status,payStatus,startTime,endTime,professionName,user);
        return new ResultPage<>(total == null ? 0 : total,byUserOrderInfoBvo != null ? byUserOrderInfoBvo.getPrice() : null,byUserOrderInfoBvo != null ? byUserOrderInfoBvo.getDeposit() : null,requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    @RequestMapping(value = "/getOrderDetailList")
    @ResponseBody
    public ResultPage getOrderDetailList(HttpServletRequest request,@RequestParam(value = "orderId",required = false) Integer orderId,
                                   RequestPage requestPage) {
        Object temp = request.getSession().getAttribute("login_id");
        Integer userId = temp == null ? 0 : Integer.valueOf(temp.toString());

        List<ByUserOrderDetailInfoBvo> list = userOrderService.selectOrderDetailListByHtmlPage(userId,orderId,(requestPage.getCurPage()-1)*requestPage.getPageSize(), requestPage.getPageSize());
        int total = userOrderService.selectOrderDetailListCount(userId, orderId);
        return new ResultPage<>(total,requestPage.getPageSize(),requestPage.getCurPage(),list);
    }

    @RequestMapping(value = "/updateOrderStatus")
    @ResponseBody
    public String updateOrderStatus(@RequestParam(value = "status",required = false) Integer status,
                                @RequestParam(value = "order_id",required = false) Integer order_id,
                                    HttpServletRequest request) {

        try{
            if (order_id != null && status != null){
                Object userNametemp = request.getSession().getAttribute("login_name");
                String userName = userNametemp == null ? null : userNametemp.toString();
                User user = userService.selectByName(userName);

                ByUserOrder order = userOrderService.findByUserOrder(order_id);

                boolean flag = false;
                //管理员或者商家接单
                if((user.getUserType().intValue() == UserType.SUPER_ADMIN.getCode() || user.getId().intValue() == order.getBizUserId().intValue()) && status == OrderStatus.BIZ_RECEIVE_ORDER.getCode()){
                    flag = true;
                    User orderUser = userService.selectUserById(order.getUserId());

                    //send msg
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("code", ""+order.getId());

                    CommonUtil.sendMessage(orderUser.getMobile(), JSONObject
                            .fromObject(map).toString(), ConfigUtil
                            .getSms_template_code_order_receive());

                    String content = user.getCnName() + "已接订单" + order_id;
                    ByUserMessage userMessage = new ByUserMessage();
                    userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                    userMessage.setContent(content);
                    userMessage.setUserId(orderUser.getId());
                    userMessage.setOrderId(order_id);
                    userService.insertUserMessage(userMessage);
                }

                if (user.getId().intValue() == order.getUserId().intValue()) {
                    flag = true;
                    if (status == OrderStatus.CONFIRM_ORDER.getCode()){//用户确认完成订单
                        User bizUser = userService.selectUserById(order.getBizUserId());

                        if (bizUser.getBizDealCount() != null && bizUser.getBizDealCount() > 0) {
                            bizUser.setBizDealCount(bizUser.getBizDealCount() + 1);
                        }else{
                            bizUser.setBizDealCount(1);
                        }

                        BigDecimal commission = BigDecimal.ZERO;
                        Role role = roleService.findRoleByUserIdType(bizUser.getId(),"3");
                        BigDecimal fix = new BigDecimal(role == null ? "0" : role.getRemark());
                        fix = fix.divide(new BigDecimal("100"));
                        if (order.getPayStatus().intValue() == OrderPayStatus.PAY_ALL.getCode()){
                            commission = order.getPrice().multiply(BigDecimal.ONE.subtract(fix));
                        }else if(order.getPayStatus().intValue() == OrderPayStatus.PAY_DEPOSIT.getCode()){
//                            commission = order.getDeposit().subtract(order.getPrice().multiply(BigDecimal.ONE.subtract(fix)));
                            commission = order.getDeposit().subtract(order.getPrice().multiply(fix));
                        }

                        if (bizUser.getMoney() == null || bizUser.getMoney() == BigDecimal.ZERO) {
                            bizUser.setMoney(commission);
                        }else{
                            bizUser.setMoney(bizUser.getMoney().add(commission));
                        }
                        writeMoneyLog(bizUser, MoneyType.PAY_ORDER.getCode(), commission);
                        userService.updateUser(bizUser);
                    }else if (status == OrderStatus.CANCEL_NOT_REFUND.getCode()|| status == OrderStatus.CONFIRM_REFUND.getCode()){//用户取消订单
                        //恢复档期
                        userOrderService.deleteScheduleByOrderId(order_id);
                    }
                }

                //符合修改规则、商家订单完成、同意退款、拒绝退款
                if(flag || status == OrderStatus.BIZ_FINISH_ORDER.getCode() || status == OrderStatus.CONFIRM_REFUND.getCode() || status == OrderStatus.REFUSD_REFUND.getCode()){
                    order.setStatus(status);
                    order.setUpdateTime(new DateTime());

                    userOrderService.insertByUserOrder(order);
                }
            }
        }catch (Exception e){
            logger.error("修改订单状态报错");
            return "error";
        }

        return "success";
    }

    /**
     * 订单支付
     * @param request
     * @throws IOException
     */
    @RequestMapping(value="/orderPay")
    public String ordersPay(
            @RequestParam(value = "order_id",required = true) String order_id,
            @RequestParam(value = "status",required = true) Integer status,
            @RequestParam(value = "payFor",required = false) String payFor,
            HttpServletRequest request,Model model,HttpServletResponse response) throws IOException{

        Object userNametemp = request.getSession().getAttribute("login_name");
        String userName = userNametemp == null ? null : userNametemp.toString();
        User user = userService.selectByName(userName);
        if (StringUtils.isBlank(order_id)){
            return "accessDenied";
        }

        Map<String, String> sParaTemp = new HashMap<String, String>();
        sParaTemp.put("service", AlipayConfig.service);
        sParaTemp.put("partner", AlipayConfig.partner);
        sParaTemp.put("seller_id", AlipayConfig.seller_id);
        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
        sParaTemp.put("payment_type", AlipayConfig.payment_type);
        sParaTemp.put("notify_url", AlipayConfig.notify_url);
        sParaTemp.put("return_url", AlipayConfig.return_url);
        sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
        sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);


        if (order_id.indexOf(",") != -1){
            String orderIds[] = order_id.split(",");

            if (orderIds != null && orderIds.length > 0){
                //add batch order
                BigDecimal totalPrice = BigDecimal.ZERO;
                BigDecimal totalDeposit = BigDecimal.ZERO;

                List<Integer> orderIdList = new ArrayList<Integer>();
                for (int i = 0; i < orderIds.length; i++) {
                    orderIdList.add(Integer.valueOf(orderIds[i]));
                }
                List<ByUserOrder> orderList = userOrderService.findByUserOrderList(orderIdList);

                for (ByUserOrder current : orderList){
                    totalPrice = totalPrice.add(current.getPrice());
                    totalDeposit = totalDeposit.add(current.getDeposit());
                }

                ByUserBatchPayOrder batchOrder = new ByUserBatchPayOrder();
                batchOrder.setUserId(user.getId());
                batchOrder.setBatchNum("bt-"+ MD5Util.Md5(DateUtil.dateToString(new DateTime())+ RandCharUtil.getRandStr(8)));
                batchOrder.setOrderIds(order_id);
                if (status.intValue() == OrderPayStatus.PAY_ALL.getCode()){
                    batchOrder.setPrice(totalPrice);
                    sParaTemp.put("total_fee", totalPrice.toString());
                }else{
                    batchOrder.setPrice(totalPrice);
                    sParaTemp.put("total_fee", totalDeposit.toString());
                }

                batchOrder.setPriceType(status);
                batchOrder.setCreateTime(new DateTime());
                batchOrder.setUpdateTime(new DateTime());
                batchOrder.setDescn("批量订单支付");
                batchOrder.setStatus(BaseState.DELETE.getCode());  //未付款

                userOrderService.insertByUserBatchPayOrder(batchOrder);

                sParaTemp.put("out_trade_no", batchOrder.getBatchNum());
                sParaTemp.put("subject", "博艺网订单_"+batchOrder.getBatchNum());


                sParaTemp.put("body", batchOrder.getDescn());
            }
        }else{
            ByUserOrder byUserOrder = userOrderService.findByUserOrder(Integer.valueOf(order_id));
            sParaTemp.put("out_trade_no", order_id);
            sParaTemp.put("subject", "博艺网订单_"+order_id);

            if (status.intValue() == OrderPayStatus.PAY_ALL.getCode()){
                sParaTemp.put("total_fee", byUserOrder.getPrice().toString());
                byUserOrder.setAlipaytotalfee(byUserOrder.getPrice());
            }else{
                sParaTemp.put("total_fee", byUserOrder.getDeposit().toString());
                byUserOrder.setAlipaytotalfee(byUserOrder.getDeposit());
            }
            userOrderService.insertByUserOrder(byUserOrder);
            sParaTemp.put("body", byUserOrder.getDescn());
        }

        if(StringUtil.isNotBlank(payFor) && "bank".equals(payFor)){
            response.setContentType("text/html; charset="+ DemoBase.encoding);
            List<Card> cardList = userService.findAllCard(user.getId());
            String cardId = cardList != null && cardList.size() > 0 ? cardList.get(0).getCardnumber() : null;
            Map<String, String> submitFromData = userOrderService.ordersPayByBank(sParaTemp.get("out_trade_no"),sParaTemp.get("total_fee"),cardId);

            String requestFrontUrl = SDKConfig.getConfig().getFrontRequestUrl();  //获取请求银联的前台地址：对应属性文件acp_sdk.properties文件中的acpsdk.frontTransUrl
            String html = AcpService.createAutoFormHtml(requestFrontUrl, submitFromData,DemoBase.encoding);   //生成自动跳转的Html表单
            LogUtil.writeLog("打印请求HTML，此为请求报文，为联调排查问题的依据："+html);
            //将生成的html写到浏览器中完成自动跳转打开银联支付页面；这里调用signData之后，将html写到浏览器跳转到银联页面之前均不能对html中的表单项的名称和值进行修改，如果修改会导致验签不通过
//            response.getWriter().write(html);
            model.addAttribute("sHtmlText", html);
        }else{

            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1
            //如sParaTemp.put("参数名","参数值");

            //建立请求
            String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","确认");

            model.addAttribute("sHtmlText", sHtmlText);
    //      PrintWriter out = response.getWriter();
    //      out.println(sHtmlText);
        }

        return  "/order/orderPayResult";
    }

    /**
     * 添加评论
     * @param order_id
     * @param user_stars
     * @param descn
     * @return
     */
    @RequestMapping(value = "/submitOrderComment")
    @ResponseBody
    public String submitOrderComment(@RequestParam(value = "order_id",required = false) Integer order_id,
                                     @RequestParam(value = "score",defaultValue = "5") Integer user_stars,
//                                     @RequestParam(value = "file",required = false) MultipartFile file,
                                     @RequestParam(value = "descn",required = false) String descn) {
        try {
            if (order_id != null && order_id > 0) {
                ByUserOrder byUserOrder = userOrderService.findByUserOrder(order_id);
                byUserOrder.setUserStars(user_stars);
                byUserOrder.setUserComment(descn);
                byUserOrder.setEvaluationTime(new DateTime());
//                if (file != null && file.getSize() > 0) {
//                    if (file.getSize() > 10000000) {
//                        throw new Exception("上传失败：文件大小不能超过10M");
//                    }
//
//                    String fileName = file.getOriginalFilename();
//                    int indexdot = fileName.lastIndexOf(".");
//                    String img_url = MD5Util.Md5(System.currentTimeMillis() + RandCharUtil.getRandStr(8) + MD5Util.Md5(file.getOriginalFilename())) + fileName.substring(indexdot);
//
////                FileUtil.saveFile(file.getInputStream(), PropertiesConfig.getProperty("img_upload_path", "/home")+"/"+img_url);
//                    UploadUtil.uploadData(file.getBytes(), img_url);
//                    byUserOrder.setImgUrl(img_url);
//                }
                byUserOrder.setStatus(9);
                userOrderService.insertByUserOrder(byUserOrder);
            }
        }catch (Exception e){

        }
        return "success";
    }

    /**
     * 添加备注
     * @param order_id
     * @param descn
     * @return
     */
    @RequestMapping(value = "/submitDescn")
    @ResponseBody
    public String submitDescn(@RequestParam(value = "order_id",required = false) Integer order_id,
                           @RequestParam(value = "descn",required = false) String descn) {
        if (order_id !=null && order_id > 0) {
            ByUserOrder byUserOrder = userOrderService.findByUserOrder(order_id);
            byUserOrder.setDescn(descn);

            userOrderService.insertByUserOrder(byUserOrder);
        }

        return "success";
    }

    /**
     * 添加退款
     * @param order_id
     * @param descn
     * @return
     */
    @RequestMapping(value = "/submitRefund")
    @ResponseBody
    public String submitRefund(@RequestParam(value = "order_id",required = false) Integer order_id,
                           @RequestParam(value = "descn",required = false) String descn) {
        if (order_id !=null && order_id > 0) {
            ByUserOrder byUserOrder = userOrderService.findByUserOrder(order_id);
            byUserOrder.setRefundDesn(descn);
            byUserOrder.setStatus(4);
            userOrderService.insertByUserOrder(byUserOrder);
        }

        return "success";
    }

    @RequestMapping(value = "/addDirectBuy")
    public String addDirectBuy(@RequestParam(value = "product_id",required = false) Integer product_id,
                               @RequestParam(value = "biz_user_id",required = false) Integer biz_user_id,
                               @RequestParam(value = "schedule_date",required = false) String schedule_date,
                               @RequestParam(value = "dinner_type",required = false) String dinner_type,
                               @RequestParam(value = "qty_item_1",defaultValue = "1") Integer qty_item_1,
                               @RequestParam(value = "descn",required = false) String descn,
                               @RequestParam(value = "pay_status",defaultValue = "2") Integer pay_status,
                               Model model,HttpServletRequest request) {

        Object userNametemp = request.getSession().getAttribute("login_name");
        String userName = userNametemp == null ? null : userNametemp.toString();
        User user = userService.selectByName(userName);

//        if (biz_user_id == null || biz_user_id < 1 || (biz_user_id.intValue() == user.getId().intValue())){
//            return "";
//        }

        ByUserOrder order = new ByUserOrder();
        if (product_id != null && product_id > 0) {
            ByUserBizProduct byUserBizProduct = userService.findBizProduct(product_id);
            User currentBizUser = userService.selectUserById(biz_user_id);

            order.setUserId(user.getId());

            order.setPayType(PayType.ALIPAY.getCode());
            order.setPayStatus(OrderPayStatus.NOT_PAY.getCode());
            order.setBizUserId(biz_user_id);
            order.setDescn(descn);
            order.setCreateTime(new DateTime());
            order.setUpdateTime(new DateTime());

            BigDecimal orderPrice = BigDecimal.ZERO;


            //更新订单价格
            if(qty_item_1 == null || qty_item_1 < 1){
                qty_item_1 = 1;
            }

            order.setPrice(byUserBizProduct.getCurrentPrice().multiply(new BigDecimal(qty_item_1)));
//            if (currentBizUser.getBizWorkType().intValue() == 1){ //策划师
//                order.setStatus(OrderStatus.NEW_ORDER.getCode());
//            }else{
                order.setStatus(OrderStatus.VERIFY_ORDER.getCode());
         //   }
            BigDecimal per = byUserBizProduct.getDeposit() == null ? new BigDecimal("0") : byUserBizProduct.getDeposit().divide(new BigDecimal("100"));
            if (pay_status.intValue() == OrderPayStatus.PAY_ALL.getCode()) {
                order.setDeposit(order.getPrice());
                order.setNeedPayPrice(BigDecimal.ZERO);
            }else{

                order.setDeposit(per.multiply(order.getPrice()));
                order.setNeedPayPrice(order.getPrice().subtract(order.getDeposit()));
            }

            userOrderService.insertByUserOrder(order);


            //insert order detail

            ByUserOrderDetail detail = new ByUserOrderDetail();
            detail.setOrderId(order.getId());
            detail.setUserId(user.getId());
            detail.setProductId(product_id);
            detail.setAmount(qty_item_1);
            detail.setPrice(order.getPrice());

            detail.setScheduleDate(DateUtil.getDateTime(schedule_date));
            detail.setDinnerType(dinner_type);
            detail.setBizUserId(byUserBizProduct.getUserId());
            detail.setOrderId(order.getId());
            detail.setDeposit(per.multiply(detail.getPrice()));
//            detail.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(detail.getPrice()));
            detail.setCreateTime(new DateTime());
            detail.setUpdateTime(new DateTime());
            userOrderService.insertByUserOrderDetail(detail);

            //add Schedule
            ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
            byUserBizSchedule.setUserId(biz_user_id);
            byUserBizSchedule.setScheduleDate(detail.getScheduleDate());
            byUserBizSchedule.setStatus(BaseState.NORMAL.getCode());
            byUserBizSchedule.setScheduleType(ScheduleType.getByName(detail.getDinnerType()).getCode());
            byUserBizSchedule.setOrderBy(detail.getUserId());
            byUserBizSchedule.setCreateTime(new DateTime());
            byUserBizSchedule.setUpdateTime(new DateTime());

            userOrderService.insertSchedule(byUserBizSchedule);

        }

        return "redirect:"+ PREFIX + "orderPay?order_id="+order.getId()+"&status="+pay_status;
    }

    @RequestMapping(value = "/addSchedule", method = RequestMethod.POST)
    public String addSchedule(@RequestParam(value = "schedule_date") Long schedule_date,
                              @RequestParam(value = "schedule_type") Integer schedule_type,
                              HttpServletRequest request) {
        try {
            Integer userId = Integer.valueOf(request.getSession().getAttribute("login_id").toString());
            User user = userService.selectUserById(userId);

            DateTime dateTime = new DateTime(schedule_date);

            ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
            byUserBizSchedule.setUserId(userId);
            byUserBizSchedule.setScheduleDate(dateTime);
            byUserBizSchedule.setStatus(1);
            byUserBizSchedule.setScheduleType(schedule_type);
            byUserBizSchedule.setCreateTime(new DateTime());
            byUserBizSchedule.setUpdateTime(new DateTime());

            userOrderService.insertSchedule(byUserBizSchedule);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping(value = "/delSchedule", method = RequestMethod.POST)
    public String delSchedule(@RequestParam(value = "schedule_date") Long schedule_date,
                              @RequestParam(value = "schedule_type") Integer schedule_type,
                              @RequestParam(value = "user_id") Integer user_id,
                              HttpServletRequest request) {
        try {
            DateTime dateTime = new DateTime(schedule_date);
            userOrderService.deleteSchedule(schedule_type, dateTime, user_id);
            System.out.println("未出错");
        } catch(Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * 查询订单评论数
     * @param id  商家ID
     * @return
     */
    @RequestMapping(value = "/countOrderDiscuss")
    @ResponseBody
    public Integer countOrderDiscuss(@RequestParam(value = "id",required = true) Integer id) {
        int count = 0;
        try {
            count = userOrderService.countOrderDiscuss(id);
        } catch(Exception e) {
            e.printStackTrace();
            count = 0;
        }

        return count;
    }

    /**
     * 根据用户ID和档期判断用户是否可以接单
     * @param userId 用户ID
     * @param scheduleDate 所选档期
     * @param model
     * @return 1 - 可以接单； 0 - 无法接单
     */
    @RequestMapping(value = "/isHaveOrder", method = RequestMethod.GET)
    @ResponseBody
    public String isHaveOrder(@RequestParam(value = "userId") int userId,
                              @RequestParam(value = "scheduleDate") String scheduleDate,
                              @RequestParam(value = "scheduleType") String scheduleType,
                              Model model) {
        boolean result = userOrderService.selectScheduleByUserId(userId, scheduleDate, scheduleType);
        model.addAttribute("result", result ? "1" : "0");

        Gson gson = new Gson();
        String results = gson.toJson(model);
        return results;
    }

    /**
     * 根据用户ID与档期查询是否有未完成的订单
     * @param userId 用户ID
     * @param scheduleDate 档期
     * @param model
     * @return 1 - 有未完成的订单； 0 - 没有未完成的订单
     */
    @RequestMapping(value = "/orderUnfinished", method = RequestMethod.GET)
    @ResponseBody
    public String orderUnfinished(@RequestParam(value = "userId") int userId,
                                  @RequestParam(value = "scheduleDate") String scheduleDate,
                                  @RequestParam(value = "scheduleType") String scheduleType,
                                  Model model) {
        int result = userOrderService.selectOrderUnfinished(userId, scheduleDate, scheduleType);
        model.addAttribute("result", result);
        Gson gson = new Gson();
        String results = gson.toJson(model);
        return results;
    }

    /**
     * 银联支付前台请求回调
     * */
    @RequestMapping(value="/bankPayFront")
    @ResponseBody
    public boolean bankPayFront(HttpServletRequest request, HttpServletResponse response){
        LogUtil.writeLog("FrontRcvResponse前台接收报文返回开始");

        String encoding = request.getParameter(SDKConstants.param_encoding);
        LogUtil.writeLog("返回报文中encoding=[" + encoding + "]");
        String pageResult = "";
        if (DemoBase.encoding.equalsIgnoreCase(encoding)) {
            pageResult = "/utf8_result.jsp";
        } else {
            pageResult = "/gbk_result.jsp";
        }
        Map<String, String> respParam = DemoBase.getAllRequestParam(request);

        // 打印请求报文
        LogUtil.printRequestLog(respParam);

        Map<String, String> valideData = null;
        StringBuffer page = new StringBuffer();
        if (null != respParam && !respParam.isEmpty()) {
            Iterator<Map.Entry<String, String>> it = respParam.entrySet()
                    .iterator();
            valideData = new HashMap<String, String>(respParam.size());
            while (it.hasNext()) {
                Map.Entry<String, String> e = it.next();
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                try {
                    value = new String(value.getBytes(encoding), encoding);
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                page.append("<tr><td width=\"30%\" align=\"right\">" + key
                        + "(" + key + ")</td><td>" + value + "</td></tr>");
                valideData.put(key, value);
            }
        }
        if (!AcpService.validate(valideData, encoding)) {
            page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>失败</td></tr>");
            LogUtil.writeLog("验证签名结果[失败].");
        } else {
            page.append("<tr><td width=\"30%\" align=\"right\">验证签名结果</td><td>成功</td></tr>");
            LogUtil.writeLog("验证签名结果[成功].");
            System.out.println(valideData.get("orderId")); //其他字段也可用类似方式获取

            String respCode = valideData.get("respCode");
            //判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。
        }
        request.setAttribute("result", page.toString());
//        request.getRequestDispatcher(pageResult).forward(request, response);

        LogUtil.writeLog("FrontRcvResponse前台接收报文返回结束");
        return true;
    }

    /**
     * 银联支付后台请求回调
     * */
    @RequestMapping(value="/bankPayBack")
    @ResponseBody
    public boolean bankPayBack(HttpServletRequest request, HttpServletResponse response){
        LogUtil.writeLog("BackRcvResponse接收后台通知开始");

        // 获取银联通知服务器发送的后台通知参数
//        Map<String, String> reqParam = DemoBase.getAllRequestParamStream(request);
//        LogUtil.printRequestLog(reqParam);
        String encoding = request.getParameter(SDKConstants.param_encoding);
        Map<String, String> respParam = DemoBase.getAllRequestParam(request);

        // 打印请求报文
        LogUtil.printRequestLog(respParam);

        Map<String, String> valideData = null;
        StringBuffer page = new StringBuffer();
        if (null != respParam && !respParam.isEmpty()) {
            Iterator<Map.Entry<String, String>> it = respParam.entrySet()
                    .iterator();
            valideData = new HashMap<String, String>(respParam.size());
            while (it.hasNext()) {
                Map.Entry<String, String> e = it.next();
                String key = (String) e.getKey();
                String value = (String) e.getValue();
                try {
                    value = new String(value.getBytes(encoding), encoding);
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                page.append("<tr><td width=\"30%\" align=\"right\">" + key
                        + "(" + key + ")</td><td>" + value + "</td></tr>");
                valideData.put(key, value);
            }
        }

        //重要！验证签名前不要修改reqParam中的键值对的内容，否则会验签不过
        if (!AcpService.validate(valideData, encoding)) {
            LogUtil.writeLog("验证签名结果[失败].");
            //验签失败，需解决验签问题

        } else {
            LogUtil.writeLog("验证签名结果[成功].");
            //【注：为了安全验签成功才应该写商户的成功处理逻辑】交易成功，更新商户订单状态

            String orderId =valideData.get("orderId"); //获取后台通知的数据，其他字段也可用类似方式获取
            String respCode = valideData.get("respCode");
            //判断respCode=00、A6后，对涉及资金类的交易，请再发起查询接口查询，确定交易成功后更新数据库。
            if(StringUtil.isNotBlank(respCode) && "00".equals(respCode) && StringUtil.isNotBlank(orderId) && orderId.startsWith("batch")){
                orderId = orderId.replace("batch","bt-");
                //批量支付
                ByUserBatchPayOrder batchPayOrder = userOrderService.findByUserBatchPayOrderByNum(orderId);

                String orderIds[] = batchPayOrder.getOrderIds().split(",");

                if (orderIds != null && orderIds.length > 0) {
                    List<Integer> orderIdList = new ArrayList<Integer>();
                    List<Integer> bizUserIdList = new ArrayList<Integer>();
                    for (int i = 0; i < orderIds.length; i++) {
                        orderIdList.add(Integer.valueOf(orderIds[i]));
                    }
                    List<ByUserOrder> orderList = userOrderService.findByUserOrderList(orderIdList);
                    Integer userId = null;
                    for (ByUserOrder current : orderList) {
                        current.setPayType(Const.OrdersPayMethod.BANK_EASYMONEY);
                        current.setPayStatus(batchPayOrder.getPriceType());
//                            orders.setNeedPayPrice(oldOrder.getPrice().subtract(orders.getAlipaytotalfee()));

                        userOrderService.insertByUserOrder(current);
                        userId = current.getUserId();
                        bizUserIdList.add(current.getBizUserId());
                        ByMoneyLog byMoneyLog = new ByMoneyLog();
                        byMoneyLog.setUserId(current.getBizUserId());
                        byMoneyLog.setMoneyType(1);
                        if (batchPayOrder.getPriceType().intValue() == OrderPayStatus.PAY_ALL.getCode()){
                            byMoneyLog.setAmount(current.getPrice());
                        }else{
                            byMoneyLog.setAmount(current.getDeposit());
                        }
                        byMoneyLog.setCreateTime(new DateTime());
                        userService.insertSelectiveByMoneyLog(byMoneyLog);
                    }
                    User payUser = userService.selectUserById(userId);
                    List<User> bizUserList = new ArrayList<User>();
                    if (bizUserIdList != null && bizUserIdList.size() > 0){
                        bizUserList = userService.selectUserByIds(bizUserIdList);
                        for(User biz : bizUserList){
                            //send msg
                            Map<String, Object> map = new LinkedHashMap<String, Object>();
                            map.put("code", ""+biz.getId());


                            if (biz != null && StringUtils.isNotBlank(biz.getMobile()) && biz.getBizWorkType() != null) {
                                CommonUtil.sendMessage(biz.getMobile(), JSONObject
                                        .fromObject(map).toString(), ConfigUtil
                                        .getSms_template_code_new_order());
                                String content = (payUser != null ? payUser.getCnName() : "") + "已付款，请及时接单";
                                ByUserMessage userMessage = new ByUserMessage();
                                userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                                userMessage.setContent(content);
                                userMessage.setUserId(biz.getId());
                                userService.insertUserMessage(userMessage);
                            }
                        }
                    }
                }
            }else{
                orderId = orderId.split("boyi")[0];
                ByUserOrder byUserOrder = userOrderService.findByUserOrder(Integer.valueOf(orderId));

                //单个支付
                String totalAmount = valideData.get("txnAmt") == null ? valideData.get("txnAmt") : valideData.get("txnAmt");
                totalAmount = totalAmount == null ? "0" : totalAmount;
                byUserOrder.setAlipaytotalfee(ObjectFormatter.str2BigDecimal(totalAmount));

                byUserOrder.setPayType(Const.OrdersPayMethod.BANK_EASYMONEY);
                ByMoneyLog byMoneyLog = new ByMoneyLog();
                byMoneyLog.setUserId(byUserOrder.getBizUserId());
                byMoneyLog.setMoneyType(1);
                byMoneyLog.setCreateTime(new DateTime());

                byUserOrder.setNeedPayPrice(byUserOrder.getPrice().subtract(byUserOrder.getAlipaytotalfee()));
                if (byUserOrder.getPrice().compareTo(byUserOrder.getAlipaytotalfee()) == 0){
                    byUserOrder.setPayStatus(OrderPayStatus.PAY_ALL.getCode());
                    byMoneyLog.setAmount(byUserOrder.getPrice());
                }else {
                    byUserOrder.setPayStatus(OrderPayStatus.PAY_DEPOSIT.getCode());
                    byMoneyLog.setAmount(byUserOrder.getDeposit());
                }
                userService.insertSelectiveByMoneyLog(byMoneyLog);
                userOrderService.insertByUserOrder(byUserOrder);
                User payUser = userService.selectUserById(byUserOrder.getUserId());
                //send msg
                Map<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("code", ""+byUserOrder.getStatus());

                User bizUser = userService.selectUserById(byUserOrder.getBizUserId());
                if (bizUser != null && StringUtils.isNotBlank(bizUser.getMobile()) && bizUser.getBizWorkType() != null){
                    CommonUtil.sendMessage(bizUser.getMobile(), JSONObject
                            .fromObject(map).toString(), ConfigUtil
                            .getSms_template_code_new_order());
                    String content = (payUser != null ? payUser.getCnName() : "") + "已付款，请及时接单";
                    ByUserMessage userMessage = new ByUserMessage();
                    userMessage.setCreateTime(new DateTime(Calendar.getInstance()));
                    userMessage.setContent(content);
                    userMessage.setUserId(bizUser.getId());
                    userService.insertUserMessage(userMessage);
                }
            }

        }
        LogUtil.writeLog("BackRcvResponse接收后台通知结束");
        return true;
    }
}
